package com.bbva.general.util;

import java.io.File;
import java.net.URL;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.bbva.general.resources.mapa;

public class JUtil
{

	static Logger log = Logger.getLogger(JUtil.class); 
	
	public static Object ObtenerBean(String beanName)
	{
		ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext((getServletContext()));
		Object o = ctx.getBean(beanName);
		return o;
	}

	public static ServletContext getServletContext()
	{
		return (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
	}

	public static String ObtenerRuta(String nombrePropiedad)
	{
		String ruta = "";
		try
		{
			URL url = mapa.class.getResource(nombrePropiedad);
			File file = new File(url.toURI());
			ruta = file.getPath();
		}
		catch (Exception e)
		{
			ruta = "";
		}
		return ruta;
	}
	
	public static void setMessageError(String error) {
		FacesContext.getCurrentInstance().addMessage(null,
				new FacesMessage(FacesMessage.SEVERITY_ERROR, error, error));
	}
	
	public static void setMessageSuccess(String msg) {
		FacesContext.getCurrentInstance().addMessage(null,
				new FacesMessage(msg));
	}
	
	public static void setMessageWarning(String error) {
		FacesContext.getCurrentInstance().addMessage(null,
				new FacesMessage(FacesMessage.SEVERITY_WARN, error, error));
	}

	 public static String mostrarMensajeExcepcion(Exception e, String claseExcepcion) {
		 String mensaje = "";
		 StackTraceElement[] traza = null;
		 
		 try {
			 mensaje = 	"Excepcion:" + claseExcepcion + "\n" +
				 		"Mensaje:" + e.getMessage() + "\n" + 
			 			"Origen: ";
			 traza = e.getStackTrace();
			 
			 log.info(mensaje);
			 if(traza != null && traza.length > 0) {
				 log.info(traza[0]);
			 }
			 
			 if(traza != null && traza.length > 1) {
				 log.info(traza[1]);
			 }
			 
			 if(traza != null && traza.length > 2) {
				 log.info(traza[2]);
			 }
			 
			 if(traza != null && traza.length > 3) {
				 log.info(traza[3]);
			 }
			 
			 if(traza != null && traza.length > 4) {
				 log.info(traza[4]);
			 }
			 
			 log.info("[Util :: mostrarMensajeExcepcion] OK");
		 } catch(Exception ex) {
			 log.info("[Util :: mostrarMensajeExcepcion] Error");
		 }
		 
		 return mensaje;
	 } 

}
